package main

import (
	"github.com/gin-contrib/sessions"
	"github.com/gin-contrib/sessions/cookie"
	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	str := "password123456"
	//设置秘钥str，创建cookie的存储引擎
	store := cookie.NewStore([]byte(str))
	//使用中间件cookie，session名同cookie名
	r.Use(sessions.Sessions("my_session", store))

	r.GET("/hello", func(c *gin.Context) {
		//初始化session
		session := sessions.Default(c)
		//读取session中的值
		if session.Get("hello") != "world" {
			session.Set("hello", "world")
			session.Delete("shirdon")
			session.Save() //保存session数据
			//session.Clear() //删除整个session
		}

		c.JSON(200, gin.H{"hello": session.Get("hello")})
	})

	r.GET("/cookie", func(c *gin.Context) {
		//获取cookie值
		data, err := c.Cookie("my_session")

		if err == nil {
			//返回cookie值
			c.String(200, data)
		} else {
			c.String(200, "not found")
		}
	})

	r.Run(":8080")
}
